import { Component, OnInit, ViewChild, ElementRef, SimpleChanges } from '@angular/core';
import * as OriginChart from "chart.js";
import { polarChartColors, optimizeUnit } from "../util";

@Component({
  selector: 'polar-area',
  templateUrl: 'polar-area.component.html',
  styleUrls: ['polar-area.component.less'],
  inputs: ['data']
})
export class PolarAreaComponent implements OnInit {
  @ViewChild('polarArea', {read: ElementRef})
  polarArea: ElementRef;
  data: any;
  chartIns;
  config = {
    data: {
      datasets: [{
        data: [],
        backgroundColor: [],
        label: '' // for legend
      }],
      labels: []
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      legend: {
        position: 'right',
      },
      title: {
        display: true,
        text: 'Chart.js Polar Area Chart'
      },
      tooltips: {
        callbacks: {
          // use the label callback to change label
          label: (tooltipItems, data) => {
            let labelVal = optimizeUnit(Math.round(Math.pow(2, Math.abs(tooltipItems.yLabel))))
            return tooltipItems.yLabel > 0
              ? `${data.labels[tooltipItems.index]}: ${labelVal}`
              : `${data.labels[tooltipItems.index]}: -${labelVal}`
          }
        }
      },
      scale: {
        ticks: {
          beginAtZero: true
        },
        reverse: false
      },
      animation: {
        animateRotate: false,
        animateScale: true
      }
    }
  }
  constructor () {}

  ngOnInit () {}

  ngOnChanges (changes: SimpleChanges) {
    if (changes.data.currentValue && this.chartIns) {
      this.updataChartConfig(changes.data.currentValue)
      this.chartIns.update()
    } else if (changes.data.currentValue && !this.chartIns) {
      let polarChart = this.polarArea.nativeElement;
      this.updataChartConfig(changes.data.currentValue)
      this.chartIns = OriginChart.PolarArea(polarChart, this.config)
    }
  }

  updataChartConfig (payLoad) {
    this.config.data.labels = [...payLoad.labels];
    this.config.data.datasets = [
      {
        data: [...payLoad.data],
        backgroundColor: [...polarChartColors],
        label: '' // for legend
      }
    ]
    this.config.options.title.text = payLoad.title
  }
}